<template>
  <c-back-wrap :loading="loading" go-page="意向客户管理" :before-call-back="$goBackCall" :current-page="isEdit?'编辑':'新增'">
    <QupFormContainer :column="3">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="130px">
        <el-form-item prop="customerPhone" label="意向客户电话">
          <el-input v-model="formData.customerPhone" placeholder="意向客户电话" :disabled="isEdit" />
        </el-form-item>
        <el-form-item prop="customerName" label="意向客户姓名">
          <el-input v-model.trim="formData.customerName" placeholder="意向客户姓名" clearable />
        </el-form-item>
        <el-form-item prop="customerIdcard" label="身份证号">
          <el-input v-model="formData.customerIdcard" placeholder="身份证号" clearable />
        </el-form-item>
        <el-form-item prop="isHaveShop" label="是否有店面">
          <c-dict-select v-model="formData.isHaveShop" dict-type-code="BOOLEANS" clearable placeholder="是否有店面" style="width:100%" />
        </el-form-item>
        <el-form-item prop="shopArea" label="店面总面积(㎡)">
          <el-input v-model="formData.shopArea" v-number.float="2" placeholder="店面总面积" clearable />
        </el-form-item>
        <el-form-item prop="intendedBusiness" label="意向经营业务">
          <c-common-search-mdm v-model="formData.intendedBusiness" multiple cust-doc-code="QY037" />
        </el-form-item>
        <el-form-item prop="intendedCity" label="意向加盟城市">
          <el-input v-model="formData.intendedCity" placeholder="意向加盟城市" clearable />
        </el-form-item>
        <el-form-item prop="customerSource" label="客户来源">
          <c-dict-select v-model="formData.customerSource" dict-type-code="CTM_TOBE_CUSTOMER_DATA_FROM" clearable placeholder="客户来源" style="width:100%" />
        </el-form-item>
        <el-form-item prop="agencyCode" label="所属办事处">
          <!-- 筛选范围为启用状态的所有办事处 -->
          <c-common-search-office
            v-model="formData.agencyCode"
            :label.sync="formData.agencyName"
          />
        </el-form-item>
        <el-form-item prop="customerSex" label="性别">
          <c-common-search-mdm v-model="formData.customerSex" cust-doc-code="QY020" :show-dialog="false" />
        </el-form-item>
        <el-form-item prop="customerAge" label="年龄">
          <el-input v-model="formData.customerAge" placeholder="年龄" clearable />
        </el-form-item>
        <el-form-item prop="intendedLevel" label="意向等级">
          <Tip>
            <div slot="tip">
              A类：确定与全友合作意向，有合作实力，有合适口岸，可快速签约；<br>
              B类：明确与全友合作意向，但可能资金不足或口岸不达标；<br>
              C类：有明确投资意向，对全友或其他竞品品牌；
            </div>
            <c-dict-select v-model="formData.intendedLevel" dict-type-code="CTM_INTENTION_LEVEL" clearable placeholder="意向等级" style="width:100%" />
          </Tip>
        </el-form-item>
        <el-form-item prop="customerType" label="意向客户分类">
          <c-dict-select v-model="formData.customerType" dict-type-code="CTM_TOBE_CUSTOMER_TYPE" clearable placeholder="意向客户分类" style="width:100%" />
        </el-form-item>
        <el-form-item prop="investmentManagerId" label="招商经理">
          <c-common-search
            v-model="formData.investmentManagerId"
            url="/slm-ctm/api/v1/ctmInvestmentManager/page"
            method="POST"
            value-key="id"
            label-key="managerName"
            query-key="managerName"
            query-position="filtersRaw"
            operator="like"
            :label.sync="formData.managerName"
            :columns="[
              {
                prop: 'managerAccount',
                label: '编码'
              },
              {
                prop: 'managerName',
                label: '姓名'
              }
            ]"
            :filters-raw="[
              { 'id': 'enable', 'property': 'enable', 'value': '1', 'operator': '=' }
            ]"
          />
        </el-form-item>
        <el-form-item prop="industryQualification" label="现经营品牌/行业资历" :span="24">
          <el-input v-model="formData.industryQualification" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="现经营品牌/行业资历" clearable />
        </el-form-item>
        <el-form-item prop="specialRemarks" label="特别备注" :span="24">
          <el-input v-model="formData.specialRemarks" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="特别备注" clearable />
        </el-form-item>
        <el-form-item prop="channel" label="来源渠道">
          <c-dict-select v-model="formData.channel" dict-type-code="CTM_POTENTIAL_CUSTOMER_SOURCE" clearable placeholder="来源渠道" style="width:100%" />
        </el-form-item>
        <el-form-item v-if="isEdit" prop="followUpStage" label="跟进进度">
          <c-dict-select v-model="formData.followUpStage" dict-type-code="CTM_INTEND_CUS_FOLLOW_UP_PROGRESS" clearable placeholder="跟进进度" style="width:100%" />
        </el-form-item>
        <el-form-item prop="createBy" label="创建人">
          <span>{{ formData.createBy }}</span>
        </el-form-item>
        <el-form-item v-if="formData.followUpStage==='E'&&isEdit" prop="terminationCause" label="终止原因" :span="24">
          <el-input v-model="formData.terminationCause" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="终止原因" clearable />
        </el-form-item>
        <template v-if="isEdit">
          <el-form-item prop="createTime" label="创建时间">
            <span>{{ formData.createTime }}</span>
          </el-form-item>
          <el-form-item prop="lastUpdateBy" label="修改人">
            <span>{{ formData.lastUpdateBy }}</span>
          </el-form-item>
          <el-form-item prop="lastUpdateTime" label="修改时间">
            <span>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </template>
      </el-form>
    </QupFormContainer>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleConfirm">确定</c-button>
    </div>
  </c-back-wrap>
</template>

<script>
import { potentialCustomerDetail, potentialCustomerAdd, potentialCustomerEdit, queryManagerByAccount } from '@/api/channelTask2/potentialCustomer'
import { mapGetters } from 'vuex'
import { validIDCard } from '@/utils/validate'
import Tip from '@/components/Tip'
export default {
  name: 'AddEdit',
  components: {
    Tip
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    const validatorCustomerPhone = (r, v, c) => {
      if (/^1\d{10}$/.test(v)) {
        c()
      } else {
        if (!v) {
          c(new Error('请输入意向客户电话'))
        } else {
          c(new Error('意向客户电话格式错误'))
        }
      }
    }
    const validatorCustomerIdcard = (r, v, c) => {
      if (v === '' || v === undefined) {
        c()
      }
      if (validIDCard(v)) {
        c()
      } else {
        c(new Error('身份证号码格式有误'))
      }
    }
    const validatorFollowStage = (r, v, c) => {
      const old = this.detail.followUpStage
      if (old !== v && v !== 'E') {
        c(new Error('跟进进度只能修改为已终止'))
      } else {
        c()
      }
    }
    return {
      formData: {
        customerPhone: '',
        customerName: '',
        customerIdcard: '',
        isHaveShop: '',
        shopArea: '',
        intendedBusiness: '',
        intendedCity: '',
        customerSource: '',
        agencyCode: '',
        agencyName: '',
        customerSex: '',
        customerAge: '',
        intendedLevel: '',
        customerType: '',
        investmentManagerId: '',
        managerName: '',
        industryQualification: '',
        specialRemarks: '',
        channel: '',
        followUpStage: '',
        terminationCause: '',
        createTime: '',
        lastUpdateBy: '',
        lastUpdateTime: '',
        createBy: '',
        createName: ''
      },
      formRules: {
        customerPhone: [{ required: true, validator: validatorCustomerPhone, trigger: 'change' }],
        customerName: [{ required: true, message: '请输入意向客户姓名', trigger: 'change' }],
        isHaveShop: [{ required: true, message: '请选择是否有店面', trigger: 'change' }],
        intendedCity: [{ required: true, message: '请选择意向加盟城市', trigger: 'change' }],
        agencyCode: [{ required: true, message: '请选择所属办事处', trigger: 'change' }],
        customerSex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        customerType: [{ required: true, message: '请选择意向客户分类', trigger: 'change' }],
        channel: [{ required: true, message: '请选择来源渠道', trigger: 'change' }],
        customerIdcard: [{ validator: validatorCustomerIdcard, trigger: 'change' }],
        followUpStage: [{ required: true, validator: validatorFollowStage, trigger: 'change' }]
      },
      detail: {},
      loading: false
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    ...mapGetters(['user'])
  },
  created() {
    if (!this.isEdit) {
      this.$set(this.formData, 'createName', this.user.data.userName)
      this.$set(this.formData, 'createBy', this.user.data.account)
      this.getCurrentUserManager()
    } else {
      this.syncFormData()
    }
  },
  methods: {
    getDetailData() {
      this.loading = true
      return potentialCustomerDetail(this.id).then(res => {
        this.loading = false
        this.detail = res.data
      }).catch(() => {
        this.loading = false
      })
    },
    detail2FormData() {
      const arry = 'intendedBusiness'.split(' ')
      for (const k of Object.keys(this.formData)) {
        let v = this.detail[k]
        if (v === undefined) {
          continue
        }
        if (k === 'customerSex') {
          v = v.toString ? v.toString() : ''
        }
        if (arry.includes(k)) {
          v = v.split(',')
        }
        this.$set(this.formData, k, v)
      }
    },
    syncFormData() {
      this.getDetailData().then(this.detail2FormData)
    },
    getCurrentUserManager() {
      return queryManagerByAccount(this.user.data.account).then(userData => {
        this.$set(this.formData, 'investmentManagerId', userData.id)
        this.$set(this.formData, 'managerName', userData.userName)
      })
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleConfirm() {
      return this.$refs.form.validate().then(() => {
        const data = { ...this.formData }
        if (data.followUpStage !== 'E') {
          delete data.terminationCause
        }
        const arry = 'intendedBusiness'.split(',')
        arry.forEach(k => {
          if (data[k] instanceof Array) {
            data[k] = data[k].join(',')
          }
        })
        if (this.isEdit) {
          data.id = this.id
        }
        return (this.isEdit ? potentialCustomerEdit : potentialCustomerAdd)(data).then(() => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('opCondition')
        })
      })
    }
  }
}
</script>
